const { splitTrainingText } = require('../splite.js');
Page({
  data: {
    // 选项列表
    goalOptions: ['增肌', '减脂', '塑形', '提升体能', '改善体态'],
    durationOptions: [15, 30, 45, 60],
    preferenceOptions: ['力量训练', '有氧运动', '瑜伽普拉提', 'HIIT', '综合训练'],
    preferences: {
      fitnessGoal: '',
      dailyDuration: '',
      fitnessPreference: ''
    },
    // 添加初始值
   showPreferenceModal: false,
   isFirstLogin: false,
   showInfoForm: false, // 控制表单显示
   userInfo: {},
   plan:{},
   step:{},
   pid:0,
   number:2,
   splitResult: {
    title: '',
    items: [],
    duration: '',
    notes: '',
    trainingStatus: []
   },
   completedCount: 0,    // 已完成的训练项数量
  totalCount: 0,        // 总训练项数量
  progressPercent: 0,   // 完成百分比
  doneCount: 0 
  },
  onLoad(){
  const userInfo = wx.getStorageSync('userInfo') || {};
  console.log("进入id：",userInfo.data.id)
  this.setData({
    userInfo:userInfo
  })
  console.log("信息是：",this.data.userInfo);
  // 判断条件：未保存过身高体重且已登录
  if ( (!userInfo.data.age&&!userInfo.data.height&&!userInfo.data.weight)) {
    this.setData({
      showInfoForm: true
    });
  }


  //还没写完

  wx.request({
    url: getApp().globalData.baseUrl+'/api/plan/uid/'+userInfo.data.id, // 后端初始化接口
    method: 'GET',
    data: {},
    header: {
      'Content-Type': 'application/json',
    },
    success: (res) => {
      console.log("结果是：",res.data)
      this.setData({
        plan:res.data.data,
        pid:res.data.data.id
      })
      this.getStepData();
      console.log("最新：",this.data.plan.title)
    },
    fail: (err) => {
      console.error('初始化数据获取失败:', err);
      wx.showToast({
        title: '数据加载失败',
        icon: 'none'
      });
    },
    complete: () => {
      // 无论成功失败，都关闭加载提示
      wx.hideLoading();
      this.setData({
        loading: false
      });
    }
  });
  console.log("这里：",this.data.pid)
  
  
  },
onInfoInput(e) {
  const { field } = e.currentTarget.dataset;
  this.setData({
    [`userInfo.${field}`]: e.detail.value
  });
},
getStepData(){
  const pid = this.data.pid;
  const requestData = {
    pid: pid, 
    number: this.data.number 
  };
  console.log("pid",pid)
  // 先判断 pid 是否有效，避免无效请求
  if (!pid || pid === 0) {
    wx.showToast({ title: '暂无关联的训练计划', icon: 'none' });
    return;
  }
  wx.request({
    
    url: getApp().globalData.baseUrl+'/api/step/getStepByPidAndNumber', 
    // 后端初始化接口
    method: 'POST',
    data: requestData,
    header: {
      'Content-Type': 'application/json',
    },
    success: (res) => {
      console.log("结果是：",res.data)
      this.setData({
        step:res.data.data,
        text:res.data.data.info
      })
      console.log("step里是",this.data.step)
      console.log("step里是",this.data.step.info)
      this.splitText();
    },
    fail: (err) => {
      console.error('初始化数据获取失败:', err);
      wx.showToast({
        title: '数据加载失败',
        icon: 'none'
      });
    },
    complete: () => {
      // 无论成功失败，都关闭加载提示
      wx.hideLoading();
      this.setData({
        loading: false
      });
    }
  });
},
splitText() {
  const text = splitTrainingText(this.data.text)
  const total = text.items.length
  this.setData({
    splitResult: text,
    // 初始化状态数组，所有项目默认为"未开始"
    trainingStatus: new Array(text.items.length).fill(0),
    totalCount: total,
    completedCount: 0,
    progressPercent: 0
  });
  wx.setStorageSync('total', total)
},
saveBasicInfo() {
  const { id,age,height, weight } = this.data.userInfo;
  // 简单验证
  if (!(age>0&&height>0&&weight>0)) {
    wx.showToast({
      title: '请完善身高体重信息',
      icon: 'none'
    });
    return;
  }
  
  // 更新用户信息
  const userInfo = wx.getStorageSync('userInfo') || {};
  const updatedInfo = {
    ...userInfo,
    height,
    weight,
    age,
    id
  };
  
  // 保存到本地
  wx.setStorageSync('userInfo', updatedInfo);
  
  // 隐藏表单
  this.setData({
    userInfo:updatedInfo,
    showInfoForm: false
  });
  
  // 同步到服务器
  wx.request({
    url: getApp().globalData.baseUrl+'/api/user/updateUser', // 后端初始化接口
    method: 'POST',
    data: {

      id:this.data.userInfo.data.id,
      height:this.data.userInfo.height,
      weight:this.data.userInfo.weight,
      age:this.data.userInfo.age
    },
    header: {
      'Content-Type': 'application/json',
    },
    success: (res) => {
      console.log(res.data)
      wx.setStorageSync('userInfo', userInfo)
    },
    fail: (err) => {
      console.error('初始化数据获取失败:', err);
      wx.showToast({
        title: '数据加载失败',
        icon: 'none'
      });
    },
    complete: () => {
      // 无论成功失败，都关闭加载提示
      wx.hideLoading();
      this.setData({
        loading: false
      });
    }
  });
  
  wx.showToast({
    title: '信息保存成功',
    icon: 'success'
  });
},

  // 导航栏切换事件处理函数
  switchTab(e) {
    // 获取点击的标签页标识
    const tab = e.currentTarget.dataset.tab;
    // 根据不同标签页跳转到对应页面
    switch(tab) {
      case 'home':
        // 跳转到首页（如果当前不在首页）
        wx.switchTab({
          url: '/pages/main/main' // 首页路径，根据实际情况修改
        });
        break;
      case 'training':
        // 跳转到训练页面
        wx.switchTab({
          url: '/pages/training/training' // 训练页面路径
        });
        break;
      case 'mine':
        // 跳转到我的页面
        wx.switchTab({
          url: '/pages/mine/mine' // 我的页面路径
        });
        break;
      default:
        console.log('未知页面');
    }
  },
  showInteractionModal() {
    // 先显示偏好选择模态框，而不是直接导航
    this.setData({
      showPreferenceModal: true,
    });
  },
  // 选择每日时长
  selectDuration(e) {
    this.setData({
      'preferences.dailyDuration': e.currentTarget.dataset.value
    });
  },
  
  // 选择健身偏好
  selectPreference(e) {
    this.setData({
      'preferences.fitnessPreference': e.currentTarget.dataset.value
    });
  },
  selectGoal(e) {
    const value = e.currentTarget.dataset.value;
    console.log('选中的目标：', value); // 确认是否正确获取值
    this.setData({
      'preferences.fitnessGoal': value
    }, () => {
      console.log('更新后的数据：', this.data.preferences.fitnessGoal); // 确认是否更新成功
    });
  },
  
  // 确认偏好选择
  confirmPreferences() {
    const { fitnessGoal, dailyDuration, fitnessPreference } = this.data.preferences;
    wx.setStorageSync('target', this.data.preferences.fitnessGoal)
    wx.setStorageSync('duration', this.data.preferences.dailyDuration)
    wx.setStorageSync('preference', this.data.preferences.fitnessPreference)
    if (!fitnessGoal || !dailyDuration || !fitnessPreference) {
      wx.showToast({
        title: '请完善所有偏好设置',
        icon: 'none'
      });

      wx.request({
        url: getApp().globalData.baseUrl+'/api/step/getStepById/'+userInfo.data.id, // 后端初始化接口
        method: 'GET',
        data: {
          Info:this.data.preferences,
        },
        header: {
          'Content-Type': 'application/json',
        },
        success: (res) => {
          console.log(res.data)
          wx.setStorageSync('step', step)
          this.setData({
            step:res.data
          })
        },
        fail: (err) => {
          console.error('初始化数据获取失败:', err);
          wx.showToast({
            title: '数据加载失败',
            icon: 'none'
          });
        },
        complete: () => {
          // 无论成功失败，都关闭加载提示
          wx.hideLoading();
          this.setData({
            loading: false
          });
        }
      });
      return;
    }
    
    // 隐藏模态框
    this.setData({
      showPreferenceModal: false
    });
    
    // 导航到教练页面并携带偏好参数
    wx.navigateTo({
      url: `/pages/coach/coach?goal=${encodeURIComponent(fitnessGoal)}&duration=${encodeURIComponent(dailyDuration)}&preference=${encodeURIComponent(fitnessPreference)}`
    });
  },
  
  // 取消选择
  cancelPreferences() {
    this.setData({
      showPreferenceModal: false
    });
  },
  // 训练项目状态切换
toggleTrainingStatus(e) {
  const app = getApp();
  const index = e.currentTarget.dataset.index;
  const status = this.data.trainingStatus[index];
  let newStatus;
  let { doneCount } = this.data;
  // 根据当前状态切换到下一个状态
  switch(status) {
    case 0: // 未开始 -> 进行中
      newStatus = 1;
      break;
    case 1: // 进行中 -> 已完成
      newStatus = 2;
      app.globalData.doneCount += 1;
      break;
      case 2: 
      newStatus = 2; // 保持已完成，点击不改变
      break;
  }
  wx.setStorageSync('done', app.globalData.doneCount.toString())
  // 更新状态数组
  const newStatusArray = [...this.data.trainingStatus];
  newStatusArray[index] = newStatus;
  // 计算完成数量和百分比
  const completedCount = newStatusArray.filter(status => status === 2).length;
  const totalCount = newStatusArray.length;
  const progressPercent = totalCount > 0 ? Math.round((completedCount / totalCount) * 100) : 0;
  this.setData({
    trainingStatus: newStatusArray,
    completedCount,
    totalCount,
    progressPercent,
    doneCount: doneCount
  });
}
})
